package com.apanal.qlife.common.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.springframework.beans.factory.annotation.Autowired;

import com.apanal.qlife.common.constants.Constants;
import com.apanal.qlife.sys.model.User;
import com.apanal.qlife.sys.service.UserService;

/**
 * 
 * 系统用户设置过滤器
 * 
 * @author shuliangxing
 * 
 * @date 2015-8-3上午11:38:10
 */
public class SysUserFilter extends PathMatchingFilter {

	@Autowired
	private UserService userService;

	@Override
	protected boolean onPreHandle(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {

		String username = (String) SecurityUtils.getSubject().getPrincipal();
		User user = userService.findByUsername(username);
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		// 用户记住登录,如果用户名改变,查询出的用户会为空,此处会有死循环 TODO
		if (user == null || user.getUseId() == null) {
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/login");
			return false;
		}
		request.setAttribute(Constants.SESSION_USER, user);
		// 设置用户代理,方便org.apache.shiro.session.Session使用,查看UserOnlineMonitorController
		// 需要注意的是此处的request为org.apache.shiro.web.servlet.ShiroHttpServletRequest
		httpRequest.getSession().setAttribute("User-Agent",
				httpRequest.getHeader("User-Agent"));
		return true;
	}
}
